<template>
  <wd-popup v-model="visible" position="bottom" :style="{ height: '75%' }">
    <view class="expense-stats">
      <view class="stats-header">
        <text class="stats-title">支出统计</text>
        <wd-icon name="close" size="20px" @click="close"></wd-icon>
      </view>

      <view class="stats-content">
        <!-- 日期范围选择 -->
        <view class="date-filter">
          <view class="date-range">
            <view class="date-input" @click="openStartDatePicker">
              <text class="date-label">开始日期</text>
              <text class="date-value">{{ formatDate(startDate) }}</text>
            </view>
            <text class="date-separator">至</text>
            <view class="date-input" @click="openEndDatePicker">
              <text class="date-label">结束日期</text>
              <text class="date-value">{{ formatDate(endDate) }}</text>
            </view>
          </view>
          <view class="quick-filters">
            <text
              v-for="(filter, index) in quickFilters"
              :key="index"
              class="filter-item"
              :class="{ active: currentFilter === index }"
              @click="applyQuickFilter(index)"
              >{{ filter.name }}</text
            >
          </view>
        </view>

        <!-- 总支出 -->
        <view class="total-expense">
          <text class="total-label">总支出</text>
          <text class="total-value">¥{{ formatAmount(totalAmount) }}</text>
        </view>

        <!-- 分类统计 -->
        <view class="category-stats">
          <text class="section-title">分类统计</text>
          <view class="category-chart">
            <!-- 这里可以集成图表组件，如果有的话 -->
            <!-- 简单的条形图实现 -->
            <view v-for="item in categoryData" :key="item.category" class="chart-item">
              <view class="chart-label">
                <expense-category-icon :icon-name="item.category"></expense-category-icon>
                <text>{{ item.name }}</text>
              </view>
              <view class="chart-bar-container">
                <view class="chart-bar" :style="{ width: `${item.percentage}%`, backgroundColor: getCategoryColor(item.category) }"></view>
                <view class="chart-values">
                  <text class="chart-percentage">{{ item.percentage.toFixed(1) }}%</text>
                  <text class="chart-amount">¥{{ formatAmount(item.amount) }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 日期统计 -->
        <view class="date-stats">
          <text class="section-title">日期统计</text>
          <view class="date-chart">
            <!-- 简单的日期统计表格 -->
            <view class="date-table">
              <view class="table-header">
                <text class="table-cell">日期</text>
                <text class="table-cell">金额</text>
                <text class="table-cell">占比</text>
              </view>
              <view v-for="item in dateData" :key="item.date" class="table-row">
                <text class="table-cell">{{ formatShortDate(item.date) }}</text>
                <text class="table-cell amount">¥{{ formatAmount(item.amount) }}</text>
                <text class="table-cell">{{ item.percentage.toFixed(1) }}%</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view style="height: 0; width: 0; overflow: hidden">
      <!-- 日期选择器 -->
      <wd-datetime-picker ref="startDatePicker" v-model="startDate" title="选择开始日期" type="date" :max="endDate" @confirm="onStartDateConfirm" />

      <wd-datetime-picker ref="endDatePicker" v-model="endDate" title="选择结束日期" type="date" :min="startDate" :max="today" @confirm="onEndDateConfirm"
    /></view>
  </wd-popup>
</template>

<script>
import { EXPENSE_CATEGORIES } from "../stores/expense.js";
import ExpenseCategoryIcon from "./ExpenseCategoryIcon.vue";

export default {
  name: "ExpenseStats",
  components: {
    ExpenseCategoryIcon,
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    expenses: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    const today = new Date();
    const lastMonth = new Date(today);
    lastMonth.setMonth(today.getMonth() - 1);

    return {
      visible: false,
      startDate: lastMonth.getTime(),
      endDate: today.getTime(),
      today: today.getTime(),
      currentFilter: 1, // 默认选择"本月"
      quickFilters: [
        { name: "今日", days: 0 }, // 使用0表示今日
        { name: "本周", days: 7 },
        { name: "本月", days: 30 },
        { name: "三个月", days: 90 },
        { name: "半年", days: 180 },
        { name: "全部", days: 0 },
      ],
    };
  },
  computed: {
    // 根据日期范围过滤支出
    filteredExpenses() {
      if (!this.startDate || !this.endDate) return this.expenses;

      const start = new Date(this.startDate);
      start.setHours(0, 0, 0, 0);

      const end = new Date(this.endDate);
      end.setHours(23, 59, 59, 999);

      return this.expenses.filter((expense) => {
        const expenseDate = new Date(expense.date);
        return expenseDate >= start && expenseDate <= end;
      });
    },

    // 总支出金额
    totalAmount() {
      return this.filteredExpenses.reduce((total, expense) => total + expense.amount, 0);
    },

    // 分类统计数据
    categoryData() {
      const data = {};

      // 初始化分类数据
      EXPENSE_CATEGORIES.filter((c) => c.id !== "all").forEach((category) => {
        data[category.id] = {
          category: category.id,
          name: category.name,
          amount: 0,
          percentage: 0,
        };
      });

      // 统计各分类金额
      this.filteredExpenses.forEach((expense) => {
        if (data[expense.category]) {
          data[expense.category].amount += expense.amount;
        } else {
          data["other"].amount += expense.amount;
        }
      });

      // 计算百分比
      if (this.totalAmount > 0) {
        Object.values(data).forEach((item) => {
          item.percentage = (item.amount / this.totalAmount) * 100;
        });
      }

      // 转换为数组并按金额排序
      return Object.values(data)
        .filter((item) => item.amount > 0)
        .sort((a, b) => b.amount - a.amount);
    },

    // 日期统计数据
    dateData() {
      const data = {};

      // 按日期分组统计
      this.filteredExpenses.forEach((expense) => {
        const date = new Date(expense.date);
        const dateKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;

        if (!data[dateKey]) {
          data[dateKey] = {
            date: dateKey,
            amount: 0,
            percentage: 0,
          };
        }

        data[dateKey].amount += expense.amount;
      });

      // 计算百分比
      if (this.totalAmount > 0) {
        Object.values(data).forEach((item) => {
          item.percentage = (item.amount / this.totalAmount) * 100;
        });
      }

      // 转换为数组并按日期排序（降序）
      return Object.values(data).sort((a, b) => new Date(b.date) - new Date(a.date));
    },
  },
  watch: {
    show(val) {
      this.visible = val;
    },
    visible(val) {
      this.$emit("update:show", val);
      if (val) {
        // 默认选择"本月"
        this.applyQuickFilter(1);
      }
    },
  },
  methods: {
    close() {
      this.visible = false;
    },
    formatAmount(amount) {
      return amount.toFixed(2);
    },
    formatDate(timestamp) {
      if (!timestamp) return "";
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    formatShortDate(dateStr) {
      const date = new Date(dateStr);
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${month}/${day}`;
    },
    openStartDatePicker() {
      this.$refs.startDatePicker.open();
    },
    openEndDatePicker() {
      this.$refs.endDatePicker.open();
    },
    onStartDateConfirm({ value }) {
      this.startDate = value;
      this.currentFilter = -1; // 自定义日期范围
      this.$emit("date-range-change", this.startDate, this.endDate);
    },
    onEndDateConfirm({ value }) {
      this.endDate = value;
      this.currentFilter = -1; // 自定义日期范围
      this.$emit("date-range-change", this.startDate, this.endDate);
    },
    applyQuickFilter(index) {
      this.currentFilter = index;
      const filter = this.quickFilters[index];

      const end = new Date();
      end.setHours(23, 59, 59, 999);
      this.endDate = end.getTime();

      if (filter.days === 0 && filter.name === "全部") {
        // 全部数据，设置一个很早的开始日期
        const start = new Date("2020-01-01");
        this.startDate = start.getTime();
      } else if (filter.days === 0 && filter.name === "今日") {
        // 今日
        const start = new Date();
        start.setHours(0, 0, 0, 0);
        this.startDate = start.getTime();
      } else {
        const start = new Date();
        start.setDate(start.getDate() - filter.days);
        start.setHours(0, 0, 0, 0);
        this.startDate = start.getTime();
      }

      this.$emit("date-range-change", this.startDate, this.endDate);
    },
    getCategoryColor(category) {
      // 为不同分类设置不同颜色
      const colorMap = {
        food: "#FF9800",
        shopping: "#2196F3",
        transport: "#4CAF50",
        entertainment: "#9C27B0",
        housing: "#F44336",
        education: "#3F51B5",
        health: "#00BCD4",
        travel: "#FF5722",
        other: "#607D8B",
      };

      return colorMap[category] || "#FF8C00";
    },
  },
};
</script>

<script setup>
// Vue 3 setup script
</script>

<style lang="scss" scoped>
.expense-stats {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
  border-radius: 16px 16px 0 0;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;

  .stats-title {
    font-size: 18px;
    font-weight: 500;
    color: #333;
  }
}

.stats-content {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.date-filter {
  margin-bottom: 20px;

  .date-range {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;

    .date-input {
      flex: 1;
      padding: 10px;
      background-color: #f5f5f5;
      border-radius: 8px;

      .date-label {
        font-size: 12px;
        color: #999;
        display: block;
        margin-bottom: 4px;
      }

      .date-value {
        font-size: 14px;
        color: #333;
      }
    }

    .date-separator {
      margin: 0 10px;
      color: #999;
    }
  }

  .quick-filters {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10px;

    .filter-item {
      padding: 6px 12px;
      margin-right: 10px;
      margin-bottom: 10px;
      font-size: 12px;
      color: #666;
      background-color: #f5f5f5;
      border-radius: 20px;

      &.active {
        background-color: #ff8c00;
        color: #fff;
      }
    }
  }
}

.total-expense {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
  margin-bottom: 20px;
  background-color: #fff9f0;
  border-radius: 8px;

  .total-label {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
  }

  .total-value {
    font-size: 28px;
    font-weight: 600;
    color: #ff8c00;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
  display: block;
}

.category-stats,
.date-stats {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.chart-item {
  margin-bottom: 15px;

  .chart-label {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    .category-icon {
      margin-right: 8px;
    }

    text {
      font-size: 14px;
      color: #666;
    }
  }

  .chart-bar-container {
    position: relative;
    height: 24px;
    background-color: #f5f5f5;
    border-radius: 4px;
    overflow: hidden;

    .chart-bar {
      height: 100%;
      border-radius: 4px;
    }

    .chart-values {
      position: absolute;
      top: 0;
      right: 10px;
      height: 100%;
      display: flex;
      align-items: center;

      .chart-percentage {
        font-size: 12px;
        color: #fff;
        margin-right: 8px;
      }

      .chart-amount {
        font-size: 12px;
        color: #fff;
        font-weight: 500;
      }
    }
  }
}

.date-table {
  width: 100%;
  border-collapse: collapse;

  .table-header {
    display: flex;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
    font-weight: 500;
    color: #666;
  }

  .table-row {
    display: flex;
    padding: 10px 0;
    border-bottom: 1px solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }
  }

  .table-cell {
    flex: 1;
    font-size: 14px;
    color: #333;

    &.amount {
      color: #ff8c00;
    }
  }
}
</style>
